import { useLocation } from "react-router-dom";
import { ThemeProvider } from "@/contexts/ThemeContext";
import { AuthProvider } from "@/contexts/AuthContext";
import { Dashboard } from "@/components/Dashboard";
import PasswordGeneratorPage from "@/components/PasswordGeneratorPage";
import { logger } from "@/utils/logger";

// Version to track updates - increment this to force reload
const APP_VERSION = "2025-10-17-18:35-v2";

/**
 * AppContent component - Handles routing
 */
function AppContent() {
  logger.debug('[AppContent] ========== APPCONTENT RENDER ==========');
  
  const location = useLocation();
  logger.debug('[AppContent] Current route: ' + location.pathname);
  
  // Update version if not set
  const storedVersion = localStorage.getItem('app_version');
  if (!storedVersion) {
    logger.info('[AppContent] Setting app version: ' + APP_VERSION);
    localStorage.setItem('app_version', APP_VERSION);
  }
  
  // Check if we're on the password generator route
  if (location.pathname === '/password-generator') {
    return <PasswordGeneratorPage />;
  }

  // Always show dashboard on main window
  return <Dashboard />;
}

/**
 * Main App component - Wraps the app with providers
 */
function App() {
  logger.info('[App] ========== APP ROOT RENDER START ==========');
  
  // Check version before rendering anything
  const storedVersion = localStorage.getItem('app_version');
  const hasReloaded = sessionStorage.getItem('version_reloaded');
  
  logger.info('[App] Version check', { storedVersion, currentVersion: APP_VERSION, hasReloaded });
  
  if (storedVersion !== null && storedVersion !== APP_VERSION && !hasReloaded) {
    logger.warn('[App] Version mismatch detected - scheduling reload');
    sessionStorage.setItem('version_reloaded', 'true');
    localStorage.setItem('app_version', APP_VERSION);
    setTimeout(() => window.location.reload(), 0);
    return <div className="h-screen flex items-center justify-center bg-background">重新加载中...</div>;
  }
  
  logger.info('[App] No version mismatch, rendering app...');

  return (
    <ThemeProvider>
      <AuthProvider>
        <AppContent />
      </AuthProvider>
    </ThemeProvider>
  );
}

export default App;
